package com.jvyou.mybatis.builder.parser;

import com.jvyou.mybatis.builder.config.DataSourceConfig;
import com.jvyou.mybatis.builder.config.EnvironmentConfig;
import com.jvyou.mybatis.builder.config.TransactionManagerConfig;
import com.jvyou.mybatis.exception.JvyouMybatisException;
import org.dom4j.Element;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/20 11:21
 * @Description 处理 Environment 节点相关的配置
 */
public class EnvironmentNodeHandler implements XmlConfigNodeHandler {
    @Override
    public void handle(Element element, XmlConfigContext context) {
        // 获取元素属性
        String id = element.attributeValue(ID);
        if (id == null || id.isEmpty()) {
            throw new JvyouMybatisException("Environment 配置节点的 id 属性不能为空");
        }
        Element tmElement = element.element(TRANSACTION_MANAGER);
        TransactionManagerConfig transactionManager = parseTransactionManager(tmElement, context);
        Element dsElement = element.element(DATA_SOURCE);
        DataSourceConfig dataSource = parseDataSource(dsElement);
        EnvironmentConfig environment = new EnvironmentConfig(id, transactionManager, dataSource);
        context.addEnvironment(environment);
    }

    private TransactionManagerConfig parseTransactionManager(Element element, XmlConfigContext context) {
        String type = element.attributeValue(TYPE);
        if (type == null || type.isEmpty()) {
            throw new JvyouMybatisException("transactionManager 节点的 type 属性不能为空");
        }
        return new TransactionManagerConfig(type);
    }

    private DataSourceConfig parseDataSource(Element element) {
        String factory = element.attributeValue(FACTORY);
        DataSourceConfig dataSource = new DataSourceConfig();
        dataSource.setFactory(factory);
        dataSource.setProperties(getProperties(element));
        return dataSource;
    }
}
